package org.example;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;
import org.tio.websocket.server.handler.IWsMsgHandler;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @author zhangjg
 * @desc c
 * @date 2023/04/26 09:04
 **/
@Component
public class MyWsHandler implements IWsMsgHandler {

    public static AtomicLong getClientNum() {
        return clientNum;
    }

    public static void setClientNum(AtomicLong clientNum) {
        MyWsHandler.clientNum = clientNum;
    }

    private static final Logger logger = LoggerFactory.getLogger(MyWsHandler.class);

    private static AtomicLong clientNum = new AtomicLong(0);

    @Override
    public HttpResponse handshake(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
        logger.info("handshake httpResponse={}", httpResponse);
        String user = httpRequest.getRequestLine().getPath().replaceFirst("/", "");
        Tio.bindUser(channelContext, user);
        return httpResponse;
    }

    @Override
    public void onAfterHandshaked(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
//        clientNum.incrementAndGet();
        int count = Tio.getAll(channelContext.tioConfig).getObj().size();
        clientNum.set(count);
        String bodyString = httpRequest.getBodyString();
        logger.info("握手成功 path={},channel={},body={}", httpRequest.getRequestLine().getPath(), channelContext.getId(), bodyString);
    }

    @Override
    public Object onBytes(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        logger.info("接收到bytes消息");
        return null;
    }

    @Override
    public Object onClose(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        logger.error("-------onClose");
        return null;
    }

    @Override
    public Object onText(WsRequest wsRequest, String s, ChannelContext channelContext) throws Exception {
//        logger.info("接收到文本消息：{}" , s);
        Tio.send(channelContext, WsResponse.fromText("responseMsg " + channelContext.userid + " " + s, "utf-8"));
        return null;
    }



}
